package thread;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/27 9:05
 * 生产者消费者模型  通过缓存区解决（管城法）  信号灯法（定义一个变量）
 */
public class ProducerAndConsumer {
    public static void main(String[] args) {
        Buffers buffers = new Buffers();
        new Consumer(buffers).start();
        new Producer(buffers).start();
    }
}
//生产者
class Producer extends Thread{
    private Buffers buffers;
    public Producer(Buffers buffers) {
        this.buffers = buffers;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buffers.Producers(new Milk(i));
            System.out.println("生产了"+ i);
        }
    }
}
//消费者
class Consumer extends Thread{
    private Buffers buffers;

    public Consumer(Buffers buffers) {
        this.buffers = buffers;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费了"+buffers.Consumers().id);
        }
    }
}
//产品
class Milk{
    int id;
    public Milk(int id) {
        this.id = id;
    }
}
//缓冲区
class Buffers{
    //设置缓冲区容器大小
    Milk[] milks = new Milk[1];
    //容器计数器
    int count = 0;

    //生产者生产
    public synchronized void Producers(Milk milk){
        //如果容器满了
        if(milks.length==count){
            try {
                //等待
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //生产产品
        milks[count] = milk;
        count++;
        //通知消费者消费
        this.notifyAll();
    }

    //消费者消费
    public synchronized Milk Consumers(){
        //当缓冲区没有牛奶，则等待生产者生产
        if (count==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //有牛奶则消费
        count--;
        Milk milk = milks[count];
        this.notifyAll();
        return milk;
    }
}
